
package com.eworking.eim.receive;

import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.packet.PacketExtension;

import com.eworking.eim.EIMChatManager;
import com.eworking.eim.EIMChatOptions;
import com.eworking.eim.message.EIMMessage;
import com.eworking.eim.message.EIMMessageTable;
import com.eworking.eim.message.EIMSendMessageThread;
import com.eworking.eim.packet.EIMCustomPacketExtension;
import com.eworking.eim.user.EIMAccountUtils;
import com.eworking.eim.util.EIMLog;

public class EIMAckMessageListener implements PacketListener {
    
    /** 日志输出标记 */
    private static final String _TAG = EIMAckMessageListener.class.getSimpleName();
    
    @Override
    public void processPacket(Packet packet) {
        try {
            Message message = (Message) packet;
            PacketExtension packetExtension = message.getExtension(EIMCustomPacketExtension._NAMESPACE);
            // 接收客户端消息回执
            if (packetExtension != null && packetExtension.getElementName().equals(EIMCustomPacketExtension._ACKED)) {
                this.processClientAckMessage(message);
            }
            // 接收服务器端消息回执
            if (packetExtension != null && packetExtension.getElementName().equals(EIMCustomPacketExtension._RECEIVED)) {
                this.processServerAckMessage(message);
            }
        } catch (Exception e) {
            EIMLog.e(_TAG, "处理接收的回执消息失败，" + e.getMessage());
        }
        
    }
    
    /**
     * 处理客户端回执消息
     * 
     * @param message
     */
    private synchronized void processClientAckMessage(Message message) {
        EIMChatOptions chatOptions = EIMChatManager.getInstance().getChatOptions();
        if (chatOptions.getRequireAck()) {
            String msgId = message.getBody();
            EIMMessage tempMessage = EIMChatManager.getInstance().getMessage(msgId);
            if (tempMessage != null) {
                tempMessage.isAcked = true;
                // 更新数据库消息回执状态
                EIMMessageTable.getInstance().updateMessageAck(msgId, true);
                String account = EIMAccountUtils.getAccountFromJID(message.getFrom());
                // 接收回执消息通知
                EIMChatManager.getInstance().notifiyAckMessage(account, msgId);
            }
        }
    }
    
    /**
     * 处理服务器回执消息
     * 
     * @param message 消息实体
     */
    private synchronized void processServerAckMessage(Message message) {
        String msgId = message.getBody();
        // 收到服务端消息回执后，去掉等待
        EIMSendMessageThread.notifySendLock(msgId);
    }
}
